package com.banciyuan.bcywebview.biz.circles.smooth.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.ZhipinApi;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.biz.circles.smooth.adapter.CircleSmoothGoodsAdapter;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.DetailGoods;

/**
 * Created by squall on 2016/12/2.
 */

public class CircleSmoothGoodsFragment extends CircleBaseSmoothFragment {

    private RecyclerView recyclerView;
    private CircleSmoothGoodsAdapter circleSmoothGoodsAdapter;
    private List<DetailGoods> dlist = new ArrayList<>();
    private SwipeRefreshLayout swipeRefreshLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.circle_smooth_fragment, null);
        initArgs();
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initUi(View rootview) {
        swipeRefreshLayout = (SwipeRefreshLayout) rootview.findViewById(R.id.swipe);
        swipeRefreshLayout.setProgressViewOffset(false, UIUtils.dip2px(205, getActivity()) + getOffset(), UIUtils.dip2px(280, getActivity()) + getOffset());
        swipeRefreshLayout.setColorSchemeResources(R.color.pink, R.color.pink);

        recyclerView = (RecyclerView) rootview.findViewById(R.id.recycle);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == 0) {
                    return 2;
                } else if (position == dlist.size() + 1) {
                    return 2;
                } else {
                    return 1;
                }
            }
        });
        recyclerView.setLayoutManager(gridLayoutManager);

        circleSmoothGoodsAdapter = new CircleSmoothGoodsAdapter(dlist, getActivity());
        circleSmoothGoodsAdapter.setLoading(true);
        recyclerView.setAdapter(circleSmoothGoodsAdapter);
    }

    @Override
    protected void initAction() {
        recyclerView.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager ll = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (dy < 0) {
                    if (ll.findFirstVisibleItemPosition() == 0 && ll.getChildAt(ll.findFirstVisibleItemPosition()).getTop() > -UIUtils.dip2px(108, getActivity())) {
                        onFoldScrollListener.onScroll(dy);
                    }
                } else {
                    onFoldScrollListener.onScroll(dy);
                }
            }

            @Override
            public void onTop() {
                onFoldScrollListener.onTop();
            }

            @Override
            public void onBottom() {
                if (!loading && !end_flag) {
                    page++;
                    initData();
                }
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loading = false;
                end_flag = false;
                page = 1;
                initData();
            }
        });
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + ZhipinApi.getListHotCore();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.ID, id));
        pairs.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        List<DetailGoods> templist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<DetailGoods>>() {
                        }.getType());
                        renderData(popIlegal(templist));
                    } else {
                        loading = false;
                        swipeRefreshLayout.setRefreshing(false);
                    }
                } catch (Exception e) {
                    loading = false;
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loading = false;
                swipeRefreshLayout.setRefreshing(false);
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        VolleyQueue.getRquest(getActivity()).add(requestParam);
    }

    private List<DetailGoods> popIlegal(List<DetailGoods> templist) {
        List<DetailGoods> ilegal = new ArrayList<>();
        for (DetailGoods d : templist) {
            if (TextUtils.isEmpty(d.getZg_id())) {
                ilegal.add(d);
            }
        }
        templist.removeAll(ilegal);
        return templist;
    }

    private void renderData(List<DetailGoods> templist) {
        if (page == 1) {
            dlist.clear();
        }
        dlist.addAll(templist);
        if (templist.isEmpty()) {
            end_flag = true;
        }
        if (circleSmoothGoodsAdapter == null) {
            circleSmoothGoodsAdapter = new CircleSmoothGoodsAdapter(dlist, getActivity());
        } else {
            int start = circleSmoothGoodsAdapter.getItemCount() - 1;
            circleSmoothGoodsAdapter.setLoading(false);
            if (page == 1) {
                circleSmoothGoodsAdapter.setHeight(0);
                circleSmoothGoodsAdapter.setMax(-1);
                circleSmoothGoodsAdapter.notifyDataSetChanged();
            } else {
                circleSmoothGoodsAdapter.notifyItemRangeInserted(start, templist.size());
                circleSmoothGoodsAdapter.notifyItemChanged(circleSmoothGoodsAdapter.getItemCount() - 1);
            }
        }
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void getParentHeight(int height) {
        if (!isVisibleToUser) {
            LinearLayoutManager ll = (LinearLayoutManager) recyclerView.getLayoutManager();
            int index = ll.findFirstVisibleItemPosition();
            if (index == 0 || index == -1) {
                ll.scrollToPositionWithOffset(0, height);
            }
        }
    }
}
